package main

import (
	"fmt"
	"os"

	"github.com/sniperHW/kendynet"
	"github.com/tealeg/xlsx"
)

func main() {
	xlFile, err := xlsx.OpenFile("../Attr.xlsx")
	if err != nil {
		panic(err)
	}

	sheet := xlFile.Sheets[0]
	rows := sheet.Rows[1:]

	str :=
		`
package attr

var nameToIdx map[string]int64
var idxToName map[int64]string

const(
`

	initStr :=
		`
func init() {	
	nameToIdx = map[string]int64{}
	idxToName = map[int64]string{}
`

	c := 0
	for _, row := range rows {
		id, _ := row.Cells[0].Int()
		if id >= 0 {
			name := row.Cells[2].String()
			desc := row.Cells[1].String()
			str = str + fmt.Sprintf("	%s = %d //%s\n", name, id, desc)
			initStr = initStr + fmt.Sprintf(`	nameToIdx["%s"] = %d`, name, id) + "\n"
			initStr = initStr + fmt.Sprintf(`	idxToName[%d] = "%s"`, id, name) + "\n"
			c++
		}
	}
	initStr = initStr + "}\n"
	str = str + fmt.Sprintf("	AttrMax = %d\n", c)
	str = str + ")\n"
	str = str + initStr

	str = str +
		`
func GetIdByName(name string) int64 {
	return nameToIdx[name]
}

func GetNameById(id int64) string {
	return idxToName[id]
}
`

	out_path := "../../../../common/attr/attr.go"

	f, err := os.OpenFile(out_path, os.O_RDWR, os.ModePerm)
	if err != nil {
		if os.IsNotExist(err) {
			f, err = os.Create(out_path)
			if err != nil {
				kendynet.Errorf("create %s failed:%s", out_path, err.Error())
				return
			}
		} else {
			kendynet.Errorf("open %s failed:%s", out_path, err.Error())
			return
		}
	}

	err = os.Truncate(out_path, 0)

	_, err = f.WriteString(str)

	if nil != err {
		kendynet.Errorf("%s Write error:%s\n", out_path, err.Error())
	} else {
		kendynet.Infof("%s Write ok\n", out_path)
	}

	f.Close()
}
